﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace YWM.Common.DataEncryptions
{
    public class TripleDESEncryption
    {
        /// <summary>
        /// 字符串的加密
        /// </summary>
        /// <param name="text">要加密的字符串</param>
        /// <param name="key">密钥，必须32位</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string text, string key)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 24));
            byte[] keyIV = new byte[8];
            Array.Copy(keyBytes, keyIV, keyIV.Length);
            byte[] inputByteArray = Encoding.UTF8.GetBytes(text);
            TripleDES tripleDES = TripleDES.Create();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, tripleDES.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            string str = Convert.ToBase64String(mStream.ToArray());
            return str;
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="text">加密后的字符串</param>
        /// <param name="key">密钥，必须32位</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string text, string key)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 24));
            byte[] keyIV = new byte[8];
            Array.Copy(keyBytes, keyIV, keyIV.Length);
            byte[] inputByteArray = Convert.FromBase64String(text);
            TripleDES tripleDES = TripleDES.Create();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, tripleDES.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray()).Replace("\\\\", "\\");
        }
    }
}
